﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace IcqSharp
{
    public class LoginChannelHandler //: ChannelHandler
    {
        public static void Handle(MemoryStream stream)
        {
            Packet p;

            // just received SRV_HELLO
            if (Session.hello)
            {
                Log.Write("Got  Login.Greeting");

                // greet login server
                p = new Packet(Channel.Login);
                p.Data.Write((UInt32)0x00000001);
                p.Data.WriteTLV(0x8003, (UInt32)0x00100000);
                p.Send();
                Log.Write("Sent Login.Greeting");

                // request login digest
                var uin_bytes = Session.LocalUIN.ToString().GetAsciiBytes();
                p = new Packet(Channel.Data);
                p.WriteFNACHeader((UInt16)Family.Authorization,
                    (UInt16)AuthorizationFamilySubtype.AuthRequest);
                p.Data.WriteTLV(0x01, uin_bytes);
                p.Send();
                Log.Write("Sent Data.Authorization.AuthKeyRequest");

                Session.hello = false;
                Session.CookieData = null;
            }
            else
            {
                Log.Write("Got  Login.ClientIdentityRequest");

                if (Session.CookieData != null)
                {
                    // send CLI_IDENT to communication server
                    Session.LocalSequence = Utilities.GenerateFlapSequence();
                    p = new Packet(Channel.Login);
                    p.WriteCookie(Session.CookieData);
                    p.Send();
                    Log.Write("Sent Login.ClientIdentityCookie");

                    Session.CookieData = null;
                }
                else
                {
                    // We need a cookie to identify us to the communication server
                    //NetLog_Server("Error: Connected to %s without a cookie!", "communication server");
                    Debugger.Break();
                }
            }
        }

    }
}
